package pers.bc.utils.aspect;

import com.sun.org.slf4j.internal.LoggerFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import pers.bc.utils.pub.DateUtilbc;
import pers.bc.utils.pub.LoggerUtil;
import pers.bc.utils.pub.StringUtil;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

/**
 * *
 *
 * @version 1.0<br>
 * @qualiFild MyDoneTimeAspect.java<br>
 * @author：LiBencheng<br>
 * @date Created on 2021年7月29日<br>
 */
@Aspect
@Component
public class AppMonitorRun
{
    public static Logger log = (Logger) LoggerFactory.getLogger(AppMonitorRun.class);

    @Around ("@annotation(monitorCtr)")
    public Object around(ProceedingJoinPoint joinPoint, AppMonitorRuning monitorCtr) throws Throwable
    {
        //当前的时间
        Instant starTime = Instant.now();
        // 这里获取到所有的参数值的数组
        Object[] args = joinPoint.getArgs();
        infoLog("开始调用{[%s]}的方法{[%s]},\r\n参数是：{[%s]}",
                monitorCtr.funEffect(), monitorCtr.method(), StringUtil.toString(args));
        infoLog(getClientInfo());
        Object obj = null;
        try  { obj = joinPoint.proceed();  }
        catch (Exception e)
        {
            log.error("{[%s]}的方法{[%s]}->程序异常或出错：%s", monitorCtr.funEffect(), monitorCtr.method(), StringUtil.toString(e));
            infoLog("{[%s]}的方法{[%s]}->程序异常或出错：%s", monitorCtr.funEffect(), monitorCtr.method(), StringUtil.toString(e));
            throw new RuntimeException(e);
        }
        finally
        {
            infoLog("{[%s]}的方法{[%s]}束时间是：{[%s]}一共运行：{[%s ms]}，返回参数【%s】",
                    monitorCtr.funEffect(), monitorCtr.method(), DateUtilbc.currentDateTime(),
                    ChronoUnit.MILLIS.between(starTime, Instant.now()), StringUtil.toString(obj));
            LoggerUtil.getInstance("methodLogs").debug(LoggerUtil.getSplitLine());

        }

        return obj;
    }

    private String getClientInfo( )
    {
        return String.format("客服端信息: ip[%s]，用户信息{name[%s]、code[%s]、userid[%s]、empid[%s]、userCompanyId[%s]}," +
                                     "companyId[%s]"
                , CurrentUser.getIP()
                , CurrentUser.getUserName()
                , CurrentUser.getUserCode()
                , CurrentUser.getUserID()
                , CurrentUser.getEmpID()
                , CurrentUser.getUserCurrenCompanyID()
                , CurrentUser.getUserOrgID());
    }

    private void infoLog(String msg, Object... objs)
    {
        System.out.println(DateUtilbc.currentDateTime() + "：System.out.println方法调用日志---> "
                                   + String.format(msg, objs));
        log.info("方法调用日志 --->" + String.format(msg, objs));
        LoggerUtil.getInstance("methodLogs").debug("方法调用日志 --->" + String.format(msg, objs));

    }
}
